package net.ba.map
{
	import com.google.maps.LatLng;
	import com.google.maps.Map;
	import com.google.maps.MapEvent;
	import com.google.maps.MapType;
	import com.google.maps.controls.ControlPosition;
	import com.google.maps.controls.ZoomControl;
	import com.google.maps.interfaces.IMapType;
	
	import flash.events.Event;
	import flash.geom.Point;
	
	import mx.core.Application;
	import mx.core.UIComponent;
	import mx.events.ResizeEvent;

	public class MapController extends UIComponent
	{
		
		public var map:Map;
		public var oneDegreeGraticule:GridOverlay;
		
		private var customMapType:IMapType 
		private var tileLayers:Array;
		private var normalMapType:IMapType;
		public var activeServerLayer:ActiveServerLayer;		
		
		public function MapController():void {
			startMap();
			addEventListener(ResizeEvent.RESIZE,onMapResized);
		}
		
		private function startMap():void {
			map = new Map();
	    	map.key = Application.application.parameters.gmapKey;
	    	map.version = "1.5";
	    	map.addEventListener(MapEvent.MAP_READY, onMapReady);
	
	    	this.addChild(map);
		}
		
	  private function onMapReady(event:Event):void {
	    map.doubleClickEnabled = false;
	    
		//var mapTypeControl:MapTypeControl = new MapTypeControl();
		var zoomControl:ZoomControl = new ZoomControl();
	    var topRight:ControlPosition = new ControlPosition(ControlPosition.ANCHOR_TOP_RIGHT, 10, 12);
	    var topLeft:ControlPosition = new ControlPosition(ControlPosition.ANCHOR_TOP_LEFT, 27, 12);
		//map.addControl(mapTypeControl);  
	    //mapTypeControl.setControlPosition(topRight);	 
		map.addControl(zoomControl);
		zoomControl.setControlPosition(topLeft);				 	    
	
		map.setCenter(new LatLng(20,20),4,MapType.PHYSICAL_MAP_TYPE);
		
		
        normalMapType = MapType.PHYSICAL_MAP_TYPE;
        tileLayers = normalMapType.getTileLayers().concat([]);
        activeServerLayer = new ActiveServerLayer(normalMapType.getTileSize());
        tileLayers.push(activeServerLayer);
        customMapType = new MapType(tileLayers,
                                                normalMapType.getProjection(),
                                                "BADE");
        map.addMapType(customMapType);
        map.setMapType(customMapType);		
        
        
        //Create the Grid Overlay
        oneDegreeGraticule = new GridOverlay();
		
		Application.application.currentState='start';   
		
	  }	
	  
	  private function onMapResized(e:Event):void {
	  	if (map!=null)
	  		map.setSize(new Point(this.width, this.height));
	  }  
	  
	  private var foo:Boolean = false;
	  public function redrawActiveServerLayer():void {
 	  	if (foo) {
			map.setSize(new Point(this.width+1, this.height+1));
			foo = false;
	  	} else {
			map.setSize(new Point(this.width-1, this.height-1));
			foo = true;
	  	} 
	  }
		
		
	public function showGrid():void {		
		oneDegreeGraticule.show();
	}	
	
	public function hideGrid():void {
		oneDegreeGraticule.hide();
	}	
		
	}
}